#include "weathermanager.h"
#include <QJsonArray>
#include <QUrlQuery>
#include <QUrl>
#include <QDebug>
#include <QDateTime>

WeatherManager::WeatherManager(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_currentReply(nullptr)
    , m_autoUpdateTimer(new QTimer(this))
    , m_currentCity("北京")
{
    // 正式环境：使用用户提供的和风天气订阅域名与KEY
    m_apiKey = "f8bbfa35000b4a17b41ef3e2de0a805b";
    m_apiUrl = "https://p87p3yujmk.re.qweatherapi.com/v7/weather/now";
    
    setupSupportedCities();
    
    // 设置自动更新定时器
    m_autoUpdateTimer->setSingleShot(false);
    connect(m_autoUpdateTimer, &QTimer::timeout, this, &WeatherManager::onAutoUpdateTimer);
    
    // 初始化获取天气数据
    QTimer::singleShot(1000, this, &WeatherManager::fetchWeatherData);

    // 初始化城市ID映射表
    initializeCityIdMap();
}

WeatherManager::~WeatherManager()
{
    if (m_currentReply) {
        m_currentReply->abort();
        m_currentReply->deleteLater();
    }
}

void WeatherManager::setCity(const QString &city)
{
    if (m_currentCity != city && m_supportedCities.contains(city)) {
        m_currentCity = city;
        emit cityChanged(city);
        fetchWeatherData();
    }
}

void WeatherManager::refreshWeatherData()
{
    fetchWeatherData();
}

void WeatherManager::startAutoUpdate(int intervalMinutes)
{
    m_autoUpdateTimer->start(intervalMinutes * 60 * 1000);
}

void WeatherManager::stopAutoUpdate()
{
    m_autoUpdateTimer->stop();
}

void WeatherManager::fetchWeatherData()
{
    // 如果有正在进行的请求，先取消
    if (m_currentReply) {
        m_currentReply->abort();
        m_currentReply->deleteLater();
        m_currentReply = nullptr;
    }
    
    QString locationId = getCityId(m_currentCity);
    if (locationId.isEmpty()) {
        qWarning() << "无法找到城市ID, 使用模拟数据:" << m_currentCity;
    simulateWeatherData();
        return;
    }

    QUrl url(m_apiUrl);
    QUrlQuery query;
    query.addQueryItem("location", locationId);
    query.addQueryItem("key", m_apiKey);
    query.addQueryItem("lang", "zh");
    query.addQueryItem("unit", "m"); // 摄氏度
    url.setQuery(query);

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::UserAgentHeader, QString("QtWeatherClient/1.0"));

    m_currentReply = m_networkManager->get(request);
    connect(m_currentReply, &QNetworkReply::finished, this, &WeatherManager::onNetworkReplyFinished);
}

void WeatherManager::simulateWeatherData()
{
    // 模拟不同城市的天气数据
    WeatherData data;
    data.city = m_currentCity;
    data.isValid = true;
    data.updateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm");
    
    // 根据城市模拟不同的天气数据
    if (m_currentCity == "北京") {
        data.weather = "晴";
        data.temperature = "22°C";
        data.humidity = "45%";
        data.windSpeed = "3级";
        data.windDirection = "东南风";
        data.pressure = "1013hPa";
        data.visibility = "10km";
    } else if (m_currentCity == "上海") {
        data.weather = "多云";
        data.temperature = "25°C";
        data.humidity = "60%";
        data.windSpeed = "2级";
        data.windDirection = "南风";
        data.pressure = "1015hPa";
        data.visibility = "8km";
    } else if (m_currentCity == "广州") {
        data.weather = "小雨";
        data.temperature = "28°C";
        data.humidity = "75%";
        data.windSpeed = "4级";
        data.windDirection = "西南风";
        data.pressure = "1008hPa";
        data.visibility = "6km";
    } else if (m_currentCity == "深圳") {
        data.weather = "阴";
        data.temperature = "26°C";
        data.humidity = "70%";
        data.windSpeed = "3级";
        data.windDirection = "南风";
        data.pressure = "1010hPa";
        data.visibility = "7km";
    } else if (m_currentCity == "杭州") {
        data.weather = "晴转多云";
        data.temperature = "24°C";
        data.humidity = "55%";
        data.windSpeed = "2级";
        data.windDirection = "东风";
        data.pressure = "1012hPa";
        data.visibility = "9km";
    } else {
        // 默认数据
        data.weather = "晴";
        data.temperature = "20°C";
        data.humidity = "50%";
        data.windSpeed = "2级";
        data.windDirection = "北风";
        data.pressure = "1013hPa";
        data.visibility = "10km";
    }
    
    m_currentWeatherData = data;
    emit weatherDataUpdated(data);
}

void WeatherManager::onNetworkReplyFinished()
{
    if (!m_currentReply) {
        return;
    }
    
    if (m_currentReply->error() == QNetworkReply::NoError) {
        QByteArray data = m_currentReply->readAll();
        parseWeatherData(data);
    } else {
        QString error = QString("网络请求失败: %1").arg(m_currentReply->errorString());
        emit errorOccurred(error);
        qDebug() << error;
        
        // 网络失败时使用模拟数据
        simulateWeatherData();
    }
    
    m_currentReply->deleteLater();
    m_currentReply = nullptr;
}

void WeatherManager::parseWeatherData(const QByteArray &data)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    
    if (error.error != QJsonParseError::NoError) {
        emit errorOccurred("JSON解析失败: " + error.errorString());
        simulateWeatherData();
        return;
    }
    
    QJsonObject obj = doc.object();
    if (obj.value("code").toString() != "200") {
        QString err = QString("HeWeather API 返回错误代码: %1").arg(obj.value("code").toString());
        emit errorOccurred(err);
        qWarning() << err;
        simulateWeatherData();
        return;
    }

    WeatherData weatherData;
    weatherData.city = m_currentCity;

    if (obj.contains("updateTime")) {
        weatherData.updateTime = obj.value("updateTime").toString().replace("T", " ").mid(0, 16);
    }

    QJsonObject now = obj.value("now").toObject();
    weatherData.weather = now.value("text").toString();
    weatherData.temperature = now.value("temp").toString() + "°C";
    weatherData.humidity = now.value("humidity").toString() + "%";
    weatherData.windSpeed = now.value("windScale").toString() + "级";
    weatherData.windDirection = now.value("windDir").toString();
    weatherData.pressure = now.value("pressure").toString() + "hPa";
    weatherData.visibility = QString::number(now.value("vis").toString().toDouble() / 1.0, 'f', 0) + "km";

    weatherData.isValid = true;
    
    m_currentWeatherData = weatherData;
    emit weatherDataUpdated(weatherData);
}

void WeatherManager::onAutoUpdateTimer()
{
    fetchWeatherData();
}

void WeatherManager::setupSupportedCities()
{
    m_supportedCities << "北京" << "上海" << "广州" << "深圳" << "杭州" 
                      << "南京" << "武汉" << "成都" << "西安" << "重庆"
                      << "天津" << "苏州" << "青岛" << "大连" << "厦门";
}

QString WeatherManager::getCityId(const QString &city) const
{
    return m_cityIdMap.value(city);
}

void WeatherManager::initializeCityIdMap()
{
    // 构建部分热门城市的location id，可在 https://console.qweather.com/geo
    m_cityIdMap["北京"] = "101010100";
    m_cityIdMap["上海"] = "101020100";
    m_cityIdMap["广州"] = "101280101";
    m_cityIdMap["深圳"] = "101280601";
    m_cityIdMap["杭州"] = "101210101";
    m_cityIdMap["南京"] = "101190101";
    m_cityIdMap["武汉"] = "101200101";
    m_cityIdMap["成都"] = "101270101";
    m_cityIdMap["西安"] = "101110101";
    m_cityIdMap["重庆"] = "101040100";
    m_cityIdMap["天津"] = "101030100";
    m_cityIdMap["苏州"] = "101190401";
    m_cityIdMap["青岛"] = "101120201";
    m_cityIdMap["大连"] = "101070201";
    m_cityIdMap["厦门"] = "101230201";
} 